import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_community/utils/eventBus.dart';
import 'package:flutter_community/utils/http.dart';
import 'package:flutter_community/utils/showToast.dart';
import 'package:flutter_community/utils/validate.dart';
import 'package:image_picker/image_picker.dart';

class HouseForm extends StatefulWidget {
  HouseForm({
    super.key,
    required this.params,
  });
  Map params;

  @override
  State<HouseForm> createState() => _HouseFormState();
}

class _HouseFormState extends State<HouseForm> {
  //表单控制器
  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _mobileController = TextEditingController();
  //定义的数据
  final Map _formData = {
    'point': '', // 小区信息
    'building': '', // 小区楼栋信息
    'room': '', // 小区房间信息
    'name': '', // 业主姓名
    'gender': 1, // 业主性别0女1男
    'mobile': '', // 业主电话
    'idcardFrontUrl': '', // 身份证正面
    'idcardBackUrl': '', // 身份证背面
  };
  @override
  void initState() {
    super.initState();
    //获取参数
    _formData.addAll(widget.params);
    _nameController.text = _formData['name'];
    _mobileController.text = _formData['mobile'];
    //去掉传参过来的status
    _formData.remove('status');
  }

//拉起底部弹窗
  _showBottomSheet(String tag) {
    showModalBottomSheet(
        context: context,
        builder: (context) {
          return SizedBox(
            height: 180,
            child: Column(
              children: [
                ListTile(
                  //左边图标
                  leading: const Icon(Icons.camera_alt),
                  title: const Text('拍照'),
                  //右边图标
                  trailing: const Icon(Icons.arrow_forward_ios_outlined),
                  onTap: () async {
                    //创建图片选择器对象
                    final ImagePicker picker = ImagePicker();
                    //拉起相机
                    final XFile? photo =
                        await picker.pickImage(source: ImageSource.camera);
                    if (photo != null) {
                      uploadImage(tag, photo.path);
                    }
                  },
                ),
                ListTile(
                  //左边图标
                  leading: const Icon(Icons.photo),
                  title: const Text('相册'),
                  //右边图标
                  trailing: const Icon(Icons.arrow_forward_ios_outlined),
                  onTap: () async {
                    //创建图片选择器对象
                    final ImagePicker picker = ImagePicker();
                    //获取图片
                    final XFile? image =
                        await picker.pickImage(source: ImageSource.gallery);
                    if (image != null) {
                      //上传图片
                      uploadImage(tag, image.path);
                    }
                  },
                ),
              ],
            ),
          );
        });
  }

//上传图片
  uploadImage(String tag, String imgInfo) async {
    try {
      // 创建formData
      FormData formData = FormData.fromMap({
        'file': await MultipartFile.fromFile(imgInfo),
      });
      //调用上传接口
      var res = await http.post('/upload', data: formData);
      print(res);
      //获取图片地址
      setState(() {
        _formData[tag] = res['data']['url'];
      });
      ToastMessage.showSuccess('上传成功');
    } catch (e) {
      ToastMessage.showFail('上传失败$e');
    } finally {
      Navigator.pop(context);
    }
  }

//提交时表单校验
  onPrimary() async {
    // 1.校验姓名和手机号
    final name = _nameController.text.trim();
    final mobile = _mobileController.text.trim();
    if (!Validate.validateName(name)) return;
    if (!Validate.validatePhone(mobile)) return;

    //2.检验正反面
    if (!Validate.validateIdCard(
        _formData['idcardFrontUrl'], _formData['idcardBackUrl'])) return;

    //3.数据赋值
    _formData['name'] = name;
    _formData['mobile'] = mobile;
    //4.提交表单
    try {
      var res = await http.post('/room', data: _formData);
      if (res['code'] != 10000) {
        ToastMessage.showFail(res['message']);
      } else {
        ToastMessage.showSuccess('提交成功');
        //数据刷新
        eventBus.fire(AddHouseRefreshEvent());
        //返回到我的房屋列表
        Navigator.popUntil(context, (route) {
          return route.settings.name == '/houseList';
        });
      }
    } catch (e) {
      ToastMessage.showFail('提交失败$e');
    }
  }

  //定义照片结构,判断有值和无值时的展示
  Widget _buildAddIdcardPhoto(String tag, String info) {
    return GestureDetector(
      onTap: () {
        //打开底部弹窗
        _showBottomSheet(tag);
      },
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Icon(
            Icons.add,
            color: Colors.blue,
          ),
          Text(
            info,
            style: const TextStyle(color: Colors.blue),
          ),
        ],
      ),
    );
  }

  //有值时展示的结构
  Widget _buildIdcardPhoto(String tag, String photoUrl) {
    return Stack(
      children: [
        //展示的身份证
        SizedBox(
          width: MediaQuery.of(context).size.width - 20,
          height: 300,
          child: Image.network(
            photoUrl,
            fit: BoxFit.contain,
          ),
        ),
        //删除图标
        Positioned(
            right: 10,
            top: 10,
            child: GestureDetector(
              onTap: () {
                setState(() {
                  _formData[tag] = '';
                });
              },
              child: const Icon(Icons.delete, color: Colors.red),
            ))
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('${_formData.containsKey('id') ? '修改' : '添加'}房屋信息'),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: Stack(
        children: [
          //顶部
          Container(
            padding: const EdgeInsets.all(10),
            child: ListView.builder(
              padding: const EdgeInsets.only(top: 10, bottom: 50),
              itemCount: 1,
              itemBuilder: (BuildContext context, int index) {
                return Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    //房屋信息
                    const Text('房屋信息',
                        style: TextStyle(fontSize: 18, color: Colors.grey)),
                    const SizedBox(
                      height: 10,
                    ),
                    Container(
                        color: Colors.white,
                        height: 60,
                        child: Container(
                          padding: const EdgeInsets.all(10),
                          child: Row(
                            children: [
                              Text(
                                  '${_formData['point']}${_formData['building']}${_formData['room']}'),
                            ],
                          ),
                        )),
                    const SizedBox(
                      height: 10,
                    ),
                    //业主信息
                    const Text(
                      '业主信息',
                      style: TextStyle(fontSize: 18, color: Colors.grey),
                    ),
                    const SizedBox(
                      height: 10,
                    ),
                    Container(
                        color: Colors.white,
                        // height: 200,
                        child: Padding(
                            padding: const EdgeInsets.all(10),
                            child: Column(
                              children: [
                                //姓名
                                TextField(
                                  maxLength: 15,
                                  controller: _nameController,
                                  keyboardType: TextInputType.name,
                                  decoration: const InputDecoration(
                                    labelText: '姓名',
                                    hintText: '请输入姓名',
                                    hintStyle: TextStyle(color: Colors.grey),
                                    border: InputBorder.none,
                                  ),
                                  // inputFormatters: [
                                  //   LengthLimitingTextInputFormatter(10),
                                  // ],
                                ),

                                //性别
                                Row(
                                  children: [
                                    const Text(
                                      '性别:',
                                      style: TextStyle(fontSize: 16),
                                    ),
                                    Radio(
                                        value: 1,
                                        groupValue: _formData['gender'],
                                        onChanged: (value) {
                                          setState(() {
                                            _formData['gender'] = value ?? '';
                                          });
                                        }),
                                    const Text(
                                      '男',
                                      style: TextStyle(fontSize: 16),
                                    ),
                                    Radio(
                                        value: 0,
                                        // 当前选中的value
                                        groupValue: _formData['gender'],
                                        onChanged: (value) {
                                          setState(() {
                                            _formData['gender'] = value ?? '';
                                          });
                                        }),
                                    const Text(
                                      '女',
                                      style: TextStyle(fontSize: 16),
                                    )
                                  ],
                                ),
                                //手机号
                                TextField(
                                  maxLength: 11,
                                  controller: _mobileController,
                                  keyboardType: TextInputType.phone,
                                  decoration: const InputDecoration(
                                    labelText: '手机号',
                                    hintText: '请输入手机号',
                                    hintStyle: TextStyle(color: Colors.grey),
                                    border: InputBorder.none,
                                  ),
                                  // inputFormatters: [
                                  //   LengthLimitingTextInputFormatter(10),
                                  // ],
                                ),
                              ],
                            ))),

                    //本人身份证照片
                    Container(
                      margin: const EdgeInsets.only(top: 10, bottom: 10),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          const Text(
                            '本人身份证照片',
                            style: TextStyle(fontSize: 18, color: Colors.grey),
                          ),
                          const SizedBox(
                            height: 10,
                          ),
                          const Text('请拍摄证件原件,并使照片中证件边缘完整,文字清晰,光面均匀'),
                          const SizedBox(
                            height: 10,
                          ),
                          //正面
                          Container(
                              color: Colors.white,
                              height: 300,
                              margin:
                                  const EdgeInsets.only(bottom: 10, top: 10),
                              width: MediaQuery.of(context).size.width,
                              child: _formData['idcardFrontUrl'] == ''
                                  ? _buildAddIdcardPhoto(
                                      'idcardFrontUrl', '上传人像面')
                                  : _buildIdcardPhoto('idcardFrontUrl',
                                      _formData['idcardFrontUrl'])),

                          //反面
                          Container(
                              color: Colors.white,
                              height: 300,
                              margin:
                                  const EdgeInsets.only(bottom: 10, top: 10),
                              width: MediaQuery.of(context).size.width,
                              child: _formData['idcardBackUrl'] == ''
                                  ? _buildAddIdcardPhoto(
                                      'idcardBackUrl', '上传国徽面照片')
                                  : _buildIdcardPhoto('idcardBackUrl',
                                      _formData['idcardBackUrl']))
                        ],
                      ),
                    ),
                  ],
                );
              },
            ),
          ),
          //底部按钮
          Positioned(
              bottom: 0,
              left: 0,
              right: 0,
              child: Container(
                  padding: const EdgeInsets.all(10),
                  // color: Colors.blue,
                  child: ElevatedButton(
                      onPressed: () {
                        onPrimary();
                      },
                      child: const Padding(
                        padding: EdgeInsets.all(8),
                        child: Column(
                          children: [
                            Icon(Icons.exit_to_app),
                            SizedBox(
                              height: 5,
                            ),
                            Text('提交审核'),
                          ],
                        ),
                      )))),
        ],
      ),
    );
  }
}
